const superagent = require('superagent');
const fs = require('fs');
const path = require('path');
const config = require('./config');
var gm = require('gm');
const tesseract = require('tesseractocr');
let a = '1';
// 下载图片
const imgDownload = (cookie) => {
  return new Promise((res, rej) => {
    console.log('刷新验证码cookie', config.codeUrl + `?a=${a}`);
    superagent
      .get(config.codeUrl + `?a=${a}`)
      .set('Cookie', cookie)
      .end(function (err, data) {
        if (err) {
          return;
        }
        const imgUrl = path.resolve(__dirname, '../code/code.jpg');
        console.log(imgUrl);
        fs.writeFile(imgUrl, data.body, 'binary', function (err) {
          console.log(88, err);
          if (err) throw err;
          res(imgUrl);
        });
      });
  });
};

// 图片降噪
const imgProcessing = (img, threshold = 60) => {
  return new Promise((resolve, reject) => {
    gm(img)
      .resize(200, 88)
      .autoOrient()
      .threshold(threshold, '%')
      .write('../code/code.gm.jpg', function (err) {
        if (!err) {
          resolve();
        } else {
          reject(err);
        }
      });
  });
};

const recognize = tesseract.withOptions({
  psm: 7,
  language: 'eng',
});
let discernCodeNumber = 0;

// 验证码识别
const discernCode = (cookie) => {
  return new Promise((res, rej) => {
    updateCode = async () => {
      a += '1';
      const imgUrl = path.resolve(__dirname, '../code/code.jpg');
      // 验证码下载
      await imgDownload(cookie);
      // 验证码降噪
      // await imgProcessing(imgUrl);
      // 验证码识别
      const recognize = tesseract.withOptions({
        psm: 7,
        language: 'eng',
      });
      let text = await recognize(imgUrl);
      text = text.replace(/[^\u4e00-\u9fa5^a-z^A-Z^0-9]/g, '');
      console.log('获取验证码为:', '[' + text + ']');
      if (text.length <= 3 && discernCodeNumber < 10) {
        console.log('\033[33m 验证码识别错误，刷新重新识别 \033[39m');
        updateCode();
        discernCodeNumber += 1;
        return;
      } else if (text.length > 4) {
        text = text.substring(0, 4);
      }
      if (discernCodeNumber >= 10) {
        console.log('\033[33m 验证码识别次数过多，请稍后重试! \033[39m');
        rej();
      }
      console.log('Code最终', text);
      res(text);
    };
    updateCode();
  });
};
module.exports = discernCode;

// let text = recognize(`${__dirname}/code/code.jpg`).then((res) => {
//   console.log(22, res);
// });
// console.log(text);
